<template>
  <div class="mapbox">
    <nav>
      <a-select
        show-search
        placeholder="input search text"
        style="width: 200px"
        :default-active-first-option="false"
        :show-arrow="false"
        :filter-option="false"
        :not-found-content="null"
        v-model="city"
        @search="handleSearch"
        @change="handleChange"
      >
        <!-- 周边 -->
        <!-- <a-select-option v-for="v in data" :key="v.address + '/' + v.location">{{ v.address }}</a-select-option> -->
        <!-- 行政区域 -->
        <a-select-option v-for="v in data" :key="v.name + '/' + v.location">{{
          v.name
        }}</a-select-option>
      </a-select>
    </nav>
    <div id="container" ref="container"></div>
  </div>
</template>

<script>
import axios from "axios";
import AMapLoader from "@amap/amap-jsapi-loader";
export default {
  name: "com-map",
  data() {
    return {
      city: undefined,
      data: [],
      isCity: true,
      map: {},
      AMap: {},
      oldMarker: "", //标点,用来删除
      oldCircle: "", //圆形,用来删除
      oldInfoWindow: "",
    };
  },
  mounted() {
    // $options 可以获取data初始值
    let initData = this.$options.data()
    console.log(initData);
  },
  beforeCreate() {
    window._AMapSecurityConfig = {
      securityJsCode: "e99ce7478e7e327ade9d1f2d2c37d6fc",
    };
    AMapLoader.load({
      key: "169b432c4986d3e46752c3bd653f24bf", // 申请好的Web端开发者Key，首次调用 load 时必填
      plugins: ["AMap.Scale",'AMap.ToolBar','AMap.PlaceSearch','AMap.MapType','AMap.AdvancedInfoWindow','AMap.HawkEye','AMap.ControlBar'],
      AMapUI: {
        // 是否加载 AMapUI，缺省不加载
        version: "1.1", // AMapUI 缺省 1.1
        mapStyle: "amap://styles/1e4e673bd7fa19abf82e0c58f6163df2",
      },
      Loca: {
        // 是否加载 Loca， 缺省不加载
        version: "1.3.2", // Loca 版本，缺省 1.3.2
      },
    })
      .then((AMap) => {
        this.$nextTick(() => this.initMap(AMap));
      })
      .catch((e) => {
        console.error(e);
      });
  },

  methods: {
    initMap(AMap) {
      this.map = new AMap.Map("container", {
        // container为容器的id
        zooms: [17, 20], //初始化地图层级
        center: [123.38, 41.8], //初始化地图中心点
        mapStyle: "amap://styles/8b328795b98cc8920f55bb4fa8d18d59", //设置地图的显示样式
        viewMode: "3D",
        pitch: 60, // 地图俯仰角度，有效范围 0 度- 83 度
        resizeEnable: true,
        features: ["bg", "road", "building",'point'],
      });
      this.map.addControl(new AMap.Scale())     //组件
      // this.map.addControl(new AMap.PlaceSearch())
      this.map.addControl(new AMap.ControlBar())
      // this.map.addControl(new AMap.HawkEye())
      // this.map.addControl(new AMap.AdvancedInfoWindow())

      this.map.on("zoomchange", (e) => {
        // console.log(this.map.getZoom(), this.map.getCenter());
      });
    },
    handleSearch(v) {
      if (!v) {
        this.data = [];
        return false;
      }
      axios({
        method: "get",
        url: "https://restapi.amap.com/v3/place/text?parameters", //周边
        // url: "https://restapi.amap.com/v3/config/district?parameters", //行政区域
        params: {
          key: "6bed841962c26cb2e7b271481debe35b",
          keywords: v,
          city: v,
        },
      }).then((res) => {
        if (res.data.pois) {
          this.data = res.data.pois;
          this.isCity = true;
        } else {
          this.isCity = true;
          let dist = res.data.districts[0];
          let patt = /(上海市|北京市|天津市|重庆市)/;
          if (patt.test(dist.name)) {
            this.data = dist.districts[0].districts;
          } else {
            this.data = dist.districts;
          }
        }
      });
    },
    handleChange(detail) {
      let map = this.map;
      let nameWD = detail.split("/");
      let lngl = nameWD[1].split(",");
      let title = nameWD[0];
      map.setCenter(lngl);
      let zoomSize = 2;
      let patt =
        /(内蒙古自治区|广西壮族自治区|西藏自治区|宁夏回族自治区|新疆维吾尔自治区)/;
      if (this.isCity) {
        zoomSize = 12;
      } else {
        if (title.includes("镇")) {
          zoomSize = 13;
        } else if (title.includes("市")) {
          zoomSize = 10;
        } else if (title.includes("省") || patt.test(title)) {
          zoomSize = 6;
        } else if (title.includes("县")) {
          zoomSize = 10;
        } else if (title.includes("区")) {
          zoomSize = 10;
        }
      }
      map.setZoom(zoomSize);

      // 标点
      let marker = new AMap.Marker({
        position: lngl, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        title: title,
      });
      marker.on("click", (e) => {
        let infoWindow = new AMap.InfoWindow({
          offset: new AMap.Pixel(0, -30),
        });
        infoWindow.setContent(e.target.De.title);
        infoWindow.open(map, e.target.getPosition());
        this.oldInfoWindow = infoWindow; //每次打开 信息窗保存一下
      });
      map.remove(this.oldInfoWindow); //每次切换 地址删除信息窗
      map.add(marker); // 将创建的点标记添加到已有的地图实例：

      // 删除 其他的点
      map.remove(this.oldMarker);
      this.oldMarker = marker;

      // 画圆
      let circle = new AMap.Circle({
        center: lngl,
        radius: 1000, //半径
        borderWeight: 3,
        strokeColor: "#FF33FF",
        strokeOpacity: 1,
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.3,
        strokeStyle: "dashed",
        strokeDasharray: [10, 10],
        // 线样式还支持 'dashed'
        fillColor: "red",
        zIndex: 50,
      });
      circle.setMap(map);

      // 删除 其他的园
      map.remove(this.oldCircle);
      this.oldCircle = circle;
    },
  },
};
</script>

<style scoped>
.mapbox {
  width: 100%;
  height: 100%;
}
#container {
  width: 100%;
  height: 100%;
}
</style>
<style>
.amap-logo {
  display: none !important;
  visibility: hidden !important;
}

.amap-copyright {
  display: none !important;
  visibility: hidden !important;
}
.mapbox {
  position: relative;
}
.mapbox nav {
  position: absolute;
  left: 10%;
  top: 10px;
  z-index: 9;
}
.amap-scalecontrol{
  left: 10% !important;
  color: white !important;
}
.amap-toolbar{
  left: 10% !important;
  top: 50px !important;
  color: white !important;
}
.amap-scale-middle{
  background: white !important;
}
.amap-maptypecontrol{
  right: 10% !important;
  color: white !important;
}
.amap-controlbar{
  right: 10% !important;
  transform: scale(.3);
}
</style>